from fastapi import APIRouter, BackgroundTasks
from starlette.requests import Request

from base.bean.api_task_bean import ApiTaskTemplateBean
from base.util.api_util import ApiUtil
from global_ver import configDao, flowDao, taskTemplateDao

templateRouter = APIRouter()


@templateRouter.post("/get_templates")
def get_templates():
    res = taskTemplateDao.get_list()

    temp_list_res = []
    for template in res:
        d = template.to_dict(orient='records')
        d['config_desc'] = configDao.get_config_by_id(template.config_id).description
        d['flow_step'] = flowDao.get_flow_by_id(template.flow_id).step
        temp_list_res.append(d)

    return ApiUtil.wrap_correct(temp_list_res)


@templateRouter.post("/delete_template")
def delete_template(bean: ApiTaskTemplateBean):
    return ApiUtil.wrap_correct("删除完成") if taskTemplateDao.delete_template(bean.id) else ApiUtil.wrap_error(
        "删除失败")


@templateRouter.post("/add_template")
def add_template(bean: ApiTaskTemplateBean):
    if bean.id is None:
        taskTemplateDao.addTemplate(bean)
    else:
        taskTemplateDao.changeTemplate(bean)
    return ApiUtil.wrap_correct("添加完成")


@templateRouter.post('/get_task_list')
def get_task_list(request: Request):
    return ApiUtil.wrap_correct(request.app.state.taskQueue.get_task_list())


@templateRouter.post('/add_temp_to_channel')
def add_temp_to_channel(bean: ApiTaskTemplateBean, request: Request, background_tasks: BackgroundTasks):
    request.app.state.taskQueue.append_queue(bean, request)
    return ApiUtil.wrap_correct("已添加进列表")


@templateRouter.post('/remove_finished_task')
def remove_finished_task(request: Request):
    request.app.state.taskQueue.remove_finished_task()
    return ApiUtil.wrap_correct("已删除")
